package com.study.rabbitmq.producer.confirm;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * 事务机制 和 发送confirm 确保发送到server的 exchange .如果此excahnge没有匹配的队列 也会丢失。
 */
public class Send1 {
	private final static String QUEUE_NAME = "tanQueue";
	private final static String EXCHANGE_NAME = "tanExchange";

	private final static String ROUTING_KEY = "tan";

	public static void main(String[] args) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.20.68");
		factory.setPort(5672);
		factory.setUsername("leke");
		factory.setPassword("leke@@@");

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, false, false, null);

		channel.queueDeclare(QUEUE_NAME, false, false, false, null);


		channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);


		channel.confirmSelect();

		String message = "Hello wrorld";
		for (int i = 0; i < 100; i++) {
			Thread.sleep(1000);
			channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, null, (message + i).getBytes());
			//阻塞 方法 同步确认 可以设置超时时间 。也可以发送一批后调用一次
			if(i%10==0)
			if (!channel.waitForConfirms()) {
				System.out.println("send message failed");
				// 重发 或者其他操作
			}
		}

		channel.close();
		connection.close();
	}
}
